package com.xkdx.guangguang.fragment.newsinfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.adapter.HomeDetailAdapter;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.shareclass.ShopAndBrandNewProduct;

public class DiscountFragment extends BaseFragment {
	private View view;
	private TextView detail, time, cheapinfo_time, cheapinfo_content;
	private Button back, btn_share;
	private ImageView im;
	private String infoID;
	private List<String> list;
	private ListView listView;
	private HomeDetailAdapter adapter;
	private ShopAndBrandNewProduct shopNewProduct;
	private LayoutInflater inflater;
	private Drawable drawable;
	private String url;
	private StringBuffer content;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	private DiscountAction discountAction;
	private DiscountModule discountModule;
	private DiscountPresistence discountPresistence;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		content = new StringBuffer();
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.shop_empty)
				.showImageOnFail(R.drawable.shop_empty)
				.resetViewBeforeLoading().cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new FadeInBitmapDisplayer(300)).build();
		infoID = getArguments().getString("infoID");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.stores_preferential, container, false);
		findView();
		setOnClick();
		showLoading();
		return view;
	}

	@Override
	public void findView() {
		listView = (ListView) view.findViewById(R.id.lv_home_detail);
		detail = (TextView) view.findViewById(R.id.detail);
		im = (ImageView) view.findViewById(R.id.stroes_preferential_im);
		time = (TextView) view.findViewById(R.id.time);
		back = (Button) view.findViewById(R.id.stores_prefrential_back);
		btn_share = (Button) view.findViewById(R.id.cheap_product_info_share);
		cheapinfo_content = (TextView) view
				.findViewById(R.id.cheapinfo_content);
		cheapinfo_time = (TextView) view.findViewById(R.id.cheapinfo_time);
		discountAction = new DiscountAction(infoID);
		discountModule = new DiscountModule();
	}

	@Override
	public void setOnClick() {
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (IConstants.isHasPush && !IConstants.isHasSelfPush) {
					IConstants.isHasPush = false;
					getActivity().finish();
				} else if (IConstants.isHasSelfPush) {
//					IConstants.isHasSelfPush = false;
					getActivity().finish();
				} else {
					getFragmentManager().popBackStack();
				}

			}
		});
		btn_share.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setShare();
			}
		});

	}

	@Override
	public void showLoading() {
		// dataLoadDialog.show();
		discountPresistence = new DiscountPresistence(this);
		((ManagerActivity) getActivity()).addCurrentTask(discountPresistence);
		discountPresistence.setActitons(discountAction);
		discountPresistence.setModule(discountModule);
		discountPresistence.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (discountPresistence != null) {
					discountPresistence.cancel(true);
				}
				getFragmentManager().popBackStack();

			}
		});

		dataLoadDialog.show();
	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			shopNewProduct = discountModule.shopAndBrandNewProduct;
			setValuse();
		} else {
			refresh(map);
		}

	}

	private void setValuse() {
		adapter = new HomeDetailAdapter(getActivity(),
				shopNewProduct.getHomeListInfoDetail());
		listView.setAdapter(adapter);
		IConstants.setListViewHeightBasedOnChildren(listView);

		if (shopNewProduct.getPictureUrlList() != null
				&& shopNewProduct.getPictureUrlList().size() > 0) {
			url = IConstants.addSuffix(shopNewProduct.getPictureUrlList()
					.get(0), "_L");
		}
		imageLoader.displayImage(url, im, options);

		detail.setText(shopNewProduct.getInfoContent());
		time.setText(shopNewProduct.getBegintime() + " 到 "
				+ shopNewProduct.getEndTime());

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	private void setShare() {
		Drawable drawable = im.getDrawable();
		if (drawable != null) {

			content.setLength(0);
			content.append(cheapinfo_content.getText());
			content.append(detail.getText());
			content.append(cheapinfo_time.getText());
			content.append(time.getText());
			Uri uri = Uri.parse(url);

			Intent intent = new Intent(Intent.ACTION_SEND);

			intent.setType("image/*");
			intent.setType("text/plain");

			List<ResolveInfo> resInfo = getActivity().getPackageManager()
					.queryIntentActivities(intent, 0);

			if (!resInfo.isEmpty()) {
				List<Intent> targetedShareIntents = new ArrayList<Intent>();
				for (ResolveInfo info : resInfo) {
					Intent targeted = new Intent(Intent.ACTION_SEND);

					targeted.setType("image/*");
					targeted.setType("text/plain");
					ActivityInfo activityInfo = info.activityInfo;

					if (activityInfo.packageName.contains("bluetooth")
							|| activityInfo.name.contains("bluetooth")) {
						continue; // 过滤蓝牙应用
					}

					if (activityInfo.packageName.contains("gm")
							|| activityInfo.name.contains("mail")) {
						targeted.putExtra(Intent.EXTRA_TEXT, content.toString());
						targeted.putExtra(Intent.EXTRA_STREAM, uri);
					} else if (activityInfo.packageName.contains("zxing")) {
						targeted.putExtra(Intent.EXTRA_TEXT, content.toString());
						targeted.putExtra(Intent.EXTRA_STREAM, uri);
					} else {
						targeted.putExtra(Intent.EXTRA_TEXT, content.toString());
						targeted.putExtra(Intent.EXTRA_STREAM, uri);
					}
					targeted.setPackage(activityInfo.packageName);
					targetedShareIntents.add(targeted);
				}
				// 分享框标题
				Intent chooserIntent = Intent.createChooser(
						targetedShareIntents.remove(0), "选择程序分享");
				if (chooserIntent == null) {
					return;
				}

				chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
						targetedShareIntents.toArray(new Parcelable[] {}));
				try {
					startActivity(chooserIntent);
				} catch (android.content.ActivityNotFoundException ex) {
					Toast.makeText(getActivity(), "没找到分享的应用",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {

		Bitmap bitmap = Bitmap.createBitmap(

		drawable.getIntrinsicWidth(),

		drawable.getIntrinsicHeight(),

		drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888

		: Bitmap.Config.RGB_565);

		return bitmap;

	}

}
